package com.beijing.cyou.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.beijing.cyou.model.UserScore;
import com.beijing.cyou.utils.NotNullHelps;
import com.beijing.cyou.utils.NumberUtil;
import com.beijing.cyou.utils.UserRedisKey;

import java.util.Set;

@Service
public class UserRedisService extends RedisBasicService {

	@Autowired
	private RedisRepository redisBasic;

	private Integer dbnum = 10 ;
	
	private String redisKey ;
	
	private String stringValue ;
	
	private String userExpTotalKey(Long userId) {
		return String.format(UserRedisKey.USER_EXP_TOTAL, userId);
	}
	
	private String userScoreTotalKey(Long userId) {
		return String.format(UserRedisKey.USER_SCORE_TOTAL, userId);
	}

	public Set<String> listUsedUserTokenKeys(){
		super.chooseRedisPool(UserRedisKey.USER_TOKEN_DB);
		redisKey = UserRedisKey.USER_TOKEN_SUMMARY;
		return redisBasic.listSet(redisKey) ;
	}

	public Set<String> listAllUserTokenKeys(){
		String vaguePattern = UserRedisKey.USER_TOKEN_PATTERN;
		super.chooseRedisPool(UserRedisKey.USER_TOKEN_DB);
		return redisBasic.listVagueKeys(vaguePattern) ;
	}

	public UserScore getUserScoreExpByUserId(Long userId)throws Exception {
		if (NotNullHelps.isNotNull(userId) == false) {
			return null;
		} else {
			UserScore userScore = new UserScore(userId);
			super.chooseRedisPool(dbnum);
			redisKey = this.userExpTotalKey(userId);
			stringValue = redisBasic.getString(redisKey);
			Integer totalExp = NumberUtil.getValueByString(stringValue);
			redisKey = this.userScoreTotalKey(userId);
			stringValue = redisBasic.getString(redisKey);
			Integer totalScore = NumberUtil.getValueByString(stringValue);
			
			userScore.setTotalScore(totalScore);
			userScore.setTotalExp(totalExp);
			return userScore;
		}
	}

}
